from threading import Thread
from hdfs.setting import HDFS_COUNT, SLEEP, HOUR
import subprocess
import datetime
from util import report
import time
from util.log import logger


class Collect(Thread):
    def __init__(self):
        super(Collect, self).__init__()

    def run(self):
        logger.info('启动HDFS采集任务')

        while True:
            time_delta = datetime.timedelta(days=1)
            time_now = datetime.datetime.now()
            yesday = time_now - time_delta
            yesday_str = yesday.strftime('%Y%m%d')

            if yesday_str.endswith(HOUR):
                logger.info('检测HDFS采集任务，执行')
                for k, v in HDFS_COUNT.items():
                    cmd = v[0]
                    app_code = v[1]
                    metrc_code = v[2]
                    status, output = subprocess.getstatusoutput(cmd.format(yesday=yesday_str))

                    if status == 0:
                        count = int(str(output).strip())
                    else:
                        count = 0

                    report_data = {
                        'appCode': app_code,
                        'metricCode': metrc_code,
                        'metricValue': count,
                        'eventTime': round(time.time() * 1000)
                    }

                    logger.info(report_data)

                    report.report(report_data)

            else:
                logger.info('检测HDFS采集任务，不执行')
                time.sleep(SLEEP)
